//
//  LeftMenuTableViewController.m
//  EZ Tracker
//
//  Created by FENGYL on 2016/11/2.
//  Copyright © 2016年 FENGYL. All rights reserved.
//

#import "OnlineCommandTableViewController.h"
#import "LocationHistoryViewController.h"
#import "NotificationsViewController.h"
#import "LeftMenuTableViewController.h"
#import "RealTimeTrackViewController.h"
#import "ZoneAlertsViewController.h"
#import "NavigatingViewController.h"
#import "SettingViewController.h"
#import "LeftMenuTableViewCell.h"
#import "LoginViewController.h"
#import "LeftMenuModel.h"
#import "UIView+XL.h"
#import "UserModel.h"

#import <FIRMessaging.h>

@interface LeftMenuTableViewController ()<UIGestureRecognizerDelegate>


@property (strong , nonatomic) NSMutableArray * dataArray;
@property (strong, nonatomic) UIPanGestureRecognizer * panGesture;
@property (strong, nonatomic) UserModel *userModel;

@end

@implementation LeftMenuTableViewController

-(UserModel *)userModel{
    
    if (!_userModel) {
        _userModel = [[UserModel alloc]init];
    }
    return _userModel;
}

-(NSMutableArray *)dataArray{
    
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]initWithCapacity:0];
        NSString * path = [[NSBundle mainBundle] pathForResource:@"LeftMenuCell" ofType:@"plist"];
        NSDictionary * dictionary = [NSDictionary dictionaryWithContentsOfFile:path];
        
        NSLog(@"dictionary %@",dictionary);
        
        for (int i = 0; i <dictionary.count; i++) {
            
            NSString * key = [NSString stringWithFormat:@"%d",i];
            
            NSDictionary * dict = [dictionary valueForKey:key];
            
            LeftMenuModel * leftMenuModel = [LeftMenuModel leftMenuModelWithDictionary:dict];
            
            [_dataArray addObject:leftMenuModel];
            
        }
        
    }
    
    return _dataArray;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.tableFooterView = [[UIView alloc]init];
    self.tableView.alpha = 0;

    self.isOpen = YES;
    
    
    self.panGesture = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(closeMenu:)];
    [self.tableView addGestureRecognizer:self.panGesture];
    
}

-(void)viewDidAppear:(BOOL)animated{
    
    if (self.isOpen) {
        [self changeViewTransform];
    }
    
    
}

#pragma mark 手势
-(void)closeMenu:(UIPanGestureRecognizer *)gesture{
    
    CGPoint translation = [gesture translationInView:gesture.view];
    NSLog(@"%@",[NSString stringWithFormat:@"(%0.0f, %0.0f)", translation.x, translation.y]);
    
    if (self.isOpen) {
        
        if (gesture.state == UIGestureRecognizerStateEnded) {
            
            if (fabs(self.tableView.superview.transform.tx) < self.tableView.width/3) {
                
                [UIView animateWithDuration:0.5 animations:^{
                    
                    self.tableView.superview.transform = CGAffineTransformIdentity;
                    
                    
                    
                    self.changeCoverViewAlpha();
                    
                }];
                
                self.isOpen = YES;
                
            }else{
                
                [UIView animateWithDuration:0.5 animations:^{
                    
                    self.tableView.superview.transform = CGAffineTransformMakeTranslation(-self.tableView.width, 0);
                    
                    
                    
                    self.changeCoverViewAlpha();
                    
                }];
                
                self.isOpen = NO;
                
            }
            
        }else{
            
            //滑动
            if (translation.x <= 0 && translation.x >= -self.tableView.width) {
                
                self.tableView.superview.transform = CGAffineTransformMakeTranslation(translation.x, 0);
                
                
                
                
                
            }
            
            self.changeCoverViewAlpha();
            
        }
    }
    
    
    
}


#pragma mark 打开关闭menu
-(void)changeViewTransform{
    
    if (!self.isOpen) {
        
        [UIView animateWithDuration:0.3 animations:^{
            
            self.tableView.superview.transform = CGAffineTransformIdentity;
            
            
            
            
        }];
        
        
    }else{
        
        [UIView animateWithDuration:0.3 animations:^{
            
            self.tableView.superview.transform = CGAffineTransformMakeTranslation(-self.tableView.width, 0);
        
            
        } completion:^(BOOL finished) {
            
            self.tableView.alpha = 1;
            
        }];
        
    }
    
    
    self.isOpen = !self.isOpen;
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataArray.count;
    
}

#pragma mark TableViewCell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    LeftMenuModel * leftMenuModel = self.dataArray[indexPath.row];
    
    LeftMenuTableViewCell * cell =[tableView dequeueReusableCellWithIdentifier:@"LeftMenuCell"];
    
    if (cell == nil) {
        
        cell = [[LeftMenuTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"LeftMenuCell"];
        
    }
    
    [cell setUpMenuIcon:leftMenuModel.icon menuLabel:leftMenuModel.menuText cellType:indexPath.row];
    
    return cell;
    
}

#pragma mark RowHeight
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 50;
    
}

#pragma mark 选中
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    LeftMenuTableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    
//    //登出
//    if ([cell.cellName isEqualToString:@"Logout"]) {
//        
//        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
//        
//    }
//    
//    //跳转RealTimeTrackViewController
//    if ([cell.cellName isEqualToString:@"Real time Track"]) {
//        
//        UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"RealTimeTrack" bundle:[NSBundle mainBundle]];
//        
//        RealTimeTrackViewController * realTimeTrackViewController = [storyBoard instantiateViewControllerWithIdentifier:@"RealTimeTrackViewController"];
//        
//        [self.parentViewController showViewController:realTimeTrackViewController sender:nil];
//        
//    }
    
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    
    UIStoryboard * storyBoard;
    RealTimeTrackViewController * realTimeTrackViewController;
    NavigatingViewController * navigatingViewController;
    LocationHistoryViewController * locationHistoryViewController;
    OnlineCommandTableViewController * onlineCommandTableViewController;
    UINavigationController * loginNavigationController;
    NotificationsViewController * notificationsViewController;
    SettingViewController *settingViewController;
    ZoneAlertsViewController *zoneAlertViewController;
    
    switch (cell.cellType) {
            
        case CellTypeRealTimeTrack:
            
            storyBoard = [UIStoryboard storyboardWithName:@"RealTimeTrack" bundle:[NSBundle mainBundle]];
            
            realTimeTrackViewController = [storyBoard instantiateViewControllerWithIdentifier:@"RealTimeTrackViewController"];
            
            [self.parentViewController showViewController:realTimeTrackViewController sender:nil];
            
            break;
            
        case CellTypeNavigating:
            
            storyBoard = [UIStoryboard storyboardWithName:@"NavigatingViewController" bundle:[NSBundle mainBundle]];
            
            navigatingViewController = [storyBoard instantiateViewControllerWithIdentifier:@"NavigatingViewController"];
            
            navigatingViewController.isSetting = NO;
            
            [self.parentViewController showViewController:navigatingViewController sender:nil];
            
            break;
            
        case CellTypeLocationHistory:
            
            storyBoard = [UIStoryboard storyboardWithName:@"LocationHistoryViewController" bundle:[NSBundle mainBundle]];
            
            locationHistoryViewController = [storyBoard instantiateViewControllerWithIdentifier:@"LocationHistoryViewController"];
            
            [self.parentViewController showViewController:locationHistoryViewController sender:nil];
            
            break;
            
        case CellTypeOnlineCommand:
            
            onlineCommandTableViewController = [[OnlineCommandTableViewController alloc]init];
            
            [self.parentViewController showViewController:onlineCommandTableViewController sender:nil];
            
            break;
            
        case CellTypeLogout:
            
            if (self.parentViewController.presentingViewController) {
                
                [userDefaults setBool:NO forKey:@"isLogin"];
                
                [self.parentViewController dismissViewControllerAnimated:YES completion:nil];
                
            }else{
                
                storyBoard = [UIStoryboard storyboardWithName:@"Login" bundle:[NSBundle mainBundle]];
                
                loginNavigationController = [storyBoard instantiateViewControllerWithIdentifier:@"LoginNavigationController"];
                
                [userDefaults setBool:NO forKey:@"isLogin"];
                
                [self presentViewController:loginNavigationController animated:YES completion:nil];
                
            }
            
            
            [[FIRMessaging messaging] unsubscribeFromTopic:[NSString stringWithFormat:@"%@%@",NC_TOPICS,self.userModel.userID]];
            
            break;
            
        case CellTypeNotifications:
            
            storyBoard = [UIStoryboard storyboardWithName:@"NotificationsTableViewController" bundle:[NSBundle mainBundle]];
            
            notificationsViewController = [storyBoard instantiateViewControllerWithIdentifier:@"NotificationsViewController"];
            
            [self showViewController:notificationsViewController sender:nil];
            
            break;
            
        case CellTypeSetting:
            
            storyBoard = [UIStoryboard storyboardWithName:@"SettingViewController" bundle:[NSBundle mainBundle]];
            
            settingViewController = [storyBoard instantiateViewControllerWithIdentifier:@"SettingViewController"];
            
            [self showViewController:settingViewController sender:nil];
            
            break;
            
        case CellTypeZoneAlerts:
            
            storyBoard = [UIStoryboard storyboardWithName:@"ZoneAlertsViewController" bundle:[NSBundle mainBundle]];
            
            zoneAlertViewController = [storyBoard instantiateViewControllerWithIdentifier:@"ZoneAlertsViewController"];
            
            [self showViewController:zoneAlertViewController sender:nil];
            
            break;
            
        default:
            break;
    }
    
    
}


/*
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath];
    
    // Configure the cell...
    
    return cell;
}
*/

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
